package leetcode;

import java.util.Arrays;

public class Q0274 {
    /**
     * O(nlogn) O(1)
     */
//    public int hIndex(int[] citations) {
//        Arrays.sort(citations);
//        for (int i = 0, k = citations.length - 1; i < citations.length; i++, k--) {
//            if (citations[k] < i + 1) {
//                return i;
//            }
//        }
//        return citations.length;
//    }

    /**
     * 二分查找 O(nlogn) O(1)
     */
    public int hIndex(int[] citations) {
        Arrays.sort(citations);
        if (citations[citations.length - 1] == 0) return 0;
        int l = 0;
        int r = citations.length - 1;
        while (l < r) {
            int mid = l + r >> 1;
            if (citations[mid] >= citations.length - mid) r = mid;
            else l = mid + 1;
        }
        return citations.length - l;
    }

    public static void main(String[] args) {
        Q0274 sl = new Q0274();
        int[] citations = {3, 0, 6, 1, 5};
        System.out.println(sl.hIndex(citations));
    }
}
